package com.shishuo.cms.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shishuo.cms.constant.ExceptionConstant;
import com.shishuo.cms.dao.UserDao;
import com.shishuo.cms.entity.GoldEntity;
import com.shishuo.cms.entity.MyNetEntity;
import com.shishuo.cms.entity.UserEntity;
import com.shishuo.cms.entity.UserRoleEntity;
import com.shishuo.cms.entity.vo.PageVo;
import com.shishuo.cms.exception.LoginException;
import com.shishuo.cms.exception.RegException;
import com.shishuo.cms.util.AuthUtils;

@Service
public class UserService extends BaseService<UserEntity, Long> {
	
	private UserDao userDao;
	@Autowired
	private MailService mailService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private MyNetService myNetService;
	@Autowired
	private GoldService goldService;
	
	
	@Autowired
	public void setUserDao(UserDao userDao) {
		setBaseDao(userDao);
		this.userDao=userDao;
	}

	public UserEntity getSingleUser(String userName) {
		return userDao.getSingleUser(userName);
	}

	public int updateUserStatus(long id, int status) {
		return userDao.updateUserStatus(id, status);
	}

	public int delUsers(Integer[] userIds) {
		return userDao.delUsers(userIds);
	}

	public boolean existUser(String userName) {
		return userDao.existUser(userName);
	}

	public Integer add(UserEntity userEntity) throws Exception
	{
		if (existUser(userEntity.getUserName()))
		{
			throw new RegException(ExceptionConstant.REG_ERROR_USER_HAS_EXIST);
		}
		UserRoleEntity userRoleEntity=userRoleService.getByRoleName("普通用户");
		if (null!=userRoleEntity) {
			userEntity.setRoleId(userRoleEntity.getId());
		}
		return userDao.add(userEntity);
	}
	
	public Integer innerReg(UserEntity userEntity,String referUserName,String centerUserName) throws Exception
	{
		if (existUser(userEntity.getUserName()))
		{
			throw new RegException(ExceptionConstant.REG_ERROR_USER_HAS_EXIST);
		}
		if (!existUser(referUserName))
		{
			throw new RegException(ExceptionConstant.REG_ERROR_REF_USER_IS_NOT_EXIST);
		}
		if (!existUser(centerUserName))
		{
			throw new RegException(ExceptionConstant.REG_ERROR_CENTER_USER_IS_NOT_EXIST);
		}
		UserEntity centerUser=userDao.getSingleUser(centerUserName);
		UserRoleEntity userRoleEntity=userRoleService.getById(centerUser.getRoleId());
		if (!userRoleEntity.getRoleName().equals("报单中心")) {
			throw new RegException(ExceptionConstant.REG_ERROR_CENTER_USER_IS_NOT_CORRECT);
		}
		UserRoleEntity userRoleEntity2=userRoleService.getByRoleName("普通用户");
		if (null!=userRoleEntity2) {
			userEntity.setRoleId(userRoleEntity2.getId());
		}
		return userDao.add(userEntity);
	}
	
	/*
	 *通过用户名密码获取用户 
	 */
	public UserEntity getByUserNameAndPassword(UserEntity userEntity) throws Exception {
		if (!existUser(userEntity.getUserName()))
		{
			throw new LoginException(ExceptionConstant.LOGIN_ERROR_USER_IS_NOT_EXIST);
		}
		UserEntity userEntityDb=this.getSingleUser(userEntity.getUserName());
		if (!userEntityDb.getPassWord().equals(userEntity.getPassWord())) {
			throw new LoginException(ExceptionConstant.LOGIN_ERROR_USERNAME_OR_PASS_IS_ERROR);
		}
		return userEntityDb;
	}

	public void updateUserPassword(UserEntity userEntity,String password,String oldpass) throws Exception {
		UserEntity userEntityDb=this.getSingleUser(userEntity.getUserName());
		if (null==userEntityDb||password==null||password.equals("")||oldpass==null||oldpass.equals("")) {
			throw new Exception(ExceptionConstant.CHANGE_PASS_ERROR);
		}
		String pwd=AuthUtils.getPassword(password,
				userEntity.getUserName());
		String oldPwd=AuthUtils.getPassword(oldpass,
				userEntity.getUserName());
		if (!oldPwd.equals(userEntityDb.getPassWord())) {
			throw new Exception(ExceptionConstant.CHANGE_PASS_ERROR_OLD_PSD_ERROR);
		}
		userDao.updateUserPassword(userEntity.getId(), pwd);
	}
	/*
	 * 邮件找回密码
	 */
	public boolean sendMailForGetPassword(String emailpass) throws Exception{
		UserEntity userEntity=userDao.getSingleUserByEmail(emailpass);
		if (null==userEntity) {
			throw new Exception(ExceptionConstant.GET_PASSWORD_ERROR);
		}
		return mailService.sendCallBackPasswordMail(emailpass,userEntity.getUserName());
	}

	public PageVo<UserEntity> getAllListPage(int pageNum) throws Exception {
		PageVo<UserEntity> pageVo = new PageVo<UserEntity>(pageNum);
		List<UserEntity> list = this.getAllList(pageVo.getOffset(), pageVo.getRows());
		pageVo.setList(list);
		pageVo.setCount(this.getAllListCount());
		return pageVo;
	}
	//加钱
	public int addUserMoney(long id, double money) {
		return userDao.updateAddUserMoney(id, money);
	}
	//加金币
	public int addUserGold(long userId, double gold) throws Exception {
		GoldEntity entity=new GoldEntity();
		entity.setGoldCount(Math.abs(gold));
		entity.setGoldMsg(((gold>0)?"新增":"扣除")+"金币");
		entity.setUserId(userId);
		entity.setPassMsg("操作成功");
		entity.setStatus(1);
		goldService.insert(entity);
		return userDao.updateAddUserGold(userId, gold);
	}

	public PageVo<UserEntity> getMyReferByUserName(String userName,int pageNum) throws Exception {
		PageVo<UserEntity> pageVo = new PageVo<UserEntity>(pageNum);
		List<UserEntity> list = userDao.getAllListByReferName(userName,pageVo.getOffset(), pageVo.getRows());
		pageVo.setList(list);
		pageVo.setCount(userDao.getAllListCountByReferName(userName));
		return pageVo;
	}

	public PageVo<UserEntity> getMyActiveUserByUserName(String userName, int pageNum) throws Exception{
		PageVo<UserEntity> pageVo = new PageVo<UserEntity>(pageNum);
		List<UserEntity> list = userDao.getMyActiveUserListByReferName(userName,pageVo.getOffset(), pageVo.getRows());
		pageVo.setList(list);
		pageVo.setCount(userDao.getMyActiveUserListCountByReferName(userName));
		return pageVo;
	}
	/**
	 * 激活用户
	 * @param userId
	 * @param loginedUserEntity
	 * @throws Exception 
	 */
	@Transactional
	public void activeUser(long userId, UserEntity loginedUserEntity,String parentUserName) throws Exception {
		double subGold=150*100;
		double referPercent=15;
		double pointParent=10;//点点积分比例
		int positionNum=0;//设置挂接到父节点的左边还是右边
		UserEntity activeUserEntity=this.getById(userId);
		if (null==activeUserEntity) {
			throw new Exception(ExceptionConstant.ACTIVE_USER_ERROR);
		}
		if (activeUserEntity.getStatus()==1) {
			throw new Exception(ExceptionConstant.ACTIVE_USER_HAS_ACTIVED);
		}
		UserEntity parentUserEntity=this.getSingleUser(parentUserName);
		if (null==parentUserEntity) {
			throw new Exception(ExceptionConstant.ACTIVE_USER_HAS_ACTIVED);
		}
		if (parentUserEntity.getStatus()!=1) {
			throw new Exception(ExceptionConstant.ACTIVE_PARIENT_USER_IS_NOT_ACTIVED);
		}
		if (loginedUserEntity.getUserGold()<subGold) {
			throw new Exception(ExceptionConstant.ACTIVE_LOGINED_USER_HAS_NOT_ENOUGH_GOLD);
		}
		List<MyNetEntity> listMyNetEntity=myNetService.getMyNetEntityByParentUserName(parentUserName);
		if (listMyNetEntity.size()==2) {
			throw new Exception(ExceptionConstant.ACTIVE_PARIENT_USER_HAS_TWO_CHILDEN);
		}else {
			if (listMyNetEntity.size()==1) {
				positionNum=1;
			}
		}
		MyNetEntity entity=new MyNetEntity();
		entity.setParentUserName(parentUserName);
		entity.setUserId(userId);
		entity.setPositionNum(positionNum);
		entity.setStatus(1);
		myNetService.insert(entity);
		//扣除登录人的积分
		addUserGold(loginedUserEntity.getId(), 0-subGold);//减金币
		//直接推荐人赚取积分
		UserEntity referUser=this.getSingleUser(activeUserEntity.getReferUserName());
		addUserGold(referUser.getId(), subGold*referPercent/100);
		//给上级用户加积分
		addUserGoldForParent(parentUserEntity, subGold*pointParent/100);
		//修改激活人状态为激活状态
		updateUserStatus(userId, 1);
		
	}
	
	private void addUserGoldForParent(UserEntity userEntity, double gold) throws Exception {
		addUserGold(userEntity.getId(), gold);//给其上级加点
		UserEntity parentUserEntity=getParentUserByUserId(userEntity.getId());
		if (null!=parentUserEntity) {
			addUserGoldForParent(parentUserEntity,gold);
		}
	}

	private UserEntity getParentUserByUserId(long id) {
		// TODO Auto-generated method stub
		return null;
	}
}